#include <iostream>
using namespace std;
#include <pthread.h>
#include <vector>
#include <unistd.h>
#include <stdio.h>
#define NUM 5

class threaddata
{
public:
public:
    pthread_t _tid;
    char _buffer[128];
    static int num;
};
int threaddata::num = 10;

void *routine(void *args)
{
    int cnt = 1;
    threaddata *ret = static_cast<threaddata *>(args);
    //pthread_detach(pthread_self());//将自己设置为分离状态，这样就不用进行线程等待
    while (cnt)
    {

        cout << ret->_buffer << endl;
        sleep(1);
        if (cnt++ == 5)
        {
            //pthread_exit(nullptr);//退出当前线程
            break;
        }
    }
    return (void *)ret->num;//10
}
int main()
{
    vector<threaddata *> tds;
    for (int i = 0; i < NUM; i++)
    {
        // 在堆上面开空间
        threaddata *ret = new threaddata();
        snprintf(ret->_buffer, sizeof(ret->_buffer), "i am new process %d", i);

        pthread_create(&ret->_tid, nullptr, routine, (void *)ret);
        tds.push_back(ret);
        pthread_detach(ret->_tid);//推荐到主线程进行线程分离
    }

    sleep(5);
    for (const auto &e : tds)
    {
        cout << "tid:" << e->_tid << endl;
    }

    sleep(3);

    //线程取消：前提是线程跑起来了
    // for(auto& e:tds){
    //     void* ret=nullptr;
    //     pthread_cancel(e->_tid);
    //     cout<<"Pthread_cancel:"<<e->_buffer<<"success"<<endl;
        
    // }




    //线程等待
    // for(auto& e:tds){
    //     void* status = nullptr;
    //     pthread_join(e->_tid,&status);
    //     cout<<"join success"<<e->_tid<<"-"<<(long long)status<<endl;
    // }

    // 主线程
    while (1)
    {
        cout << "i am old process" << endl;
        sleep(1);
    }

    return 0;
}